package com.stu.servlet;

import com.stu.dao.LoginDao;
import com.stu.dao.impl.LoginDaoImpl;
import com.stu.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取用户注册的账户和密码
        String userAccount = req.getParameter("userAccount");
        String passWord = req.getParameter("passWord");
        //利用账户和密码创建一个用户对象
        User user = new User(userAccount, passWord);
 /*       System.out.println(user.getUserAccount());
        System.out.println(user.getUserPassword());*/
        //创建LoginDao的对象
        LoginDaoImpl loginDao=new LoginDaoImpl();
       //创建一个姓的用户对象
        User newUser = null;
        try {
            //调用loginDao的根据用户账号和用户密码查询用户线详细信息的方法
            newUser = loginDao.getLogin(user);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
      /*  System.out.println(newUser.getUserName());*/
        if (newUser != null) {
            //将登录的用户会话对象设置为参数
            HttpSession session=req.getSession();
            session.setAttribute("session_newUser",newUser);
            //将置于网页blank.jsp页面作为参数传递到主页面
            req.setAttribute("mainRight", "blank.jsp");
            //登录成功,进入主界面
            req.getRequestDispatcher("mainPage.jsp").forward(req, resp);
        } else {
            //登录失败,回到登录注册界面
            req.setAttribute("message", "账户或密码有误");
            req.getRequestDispatcher("login2.jsp").forward(req, resp);

        }

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
